//
//  iPLayer_ipadViewController.m
//  iPLayer-ipad
//
//  Created by Chris Greening on 06/05/2010.
//  Copyright CMG Research 2010. All rights reserved.
//

#import "iPLayer_ipadViewController.h"
#import "Categories.h"
#import <Foundation/Foundation.h>

@interface NSObject (Swizzle)

+ (BOOL)swizzleMethod:(SEL)origSelector withMethod:(SEL)newSelector;

@end

@implementation NSObject (Swizzle)

+ (BOOL)swizzleMethod:(SEL)origSelector withMethod:(SEL)newSelector
{
    IMP origMethod = class_getInstanceMethod(self, origSelector);
    IMP newMethod = class_getInstanceMethod(self, newSelector);
	
    if (origMethod && newMethod) {
        if (class_addMethod(self, origSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
            class_replaceMethod(self, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        } else {
            method_exchangeImplementations(origMethod, newMethod);
        }
        return YES;
    }
    return NO;
}

@end

@interface NSMutableURLRequest (MyMutableURLRequest)

+ (void)setupUserAgentOverwrite;

@end

@implementation NSMutableURLRequest (MyMutableURLRequest)

- (void)newSetValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
{
    if ([field isEqualToString:@"User-Agent"]) {
		value = @"Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3";
		//value = @"SAMSUNG-SGH-i900/1.0 Opera 9.5";
	}
    [self newSetValue:value forHTTPHeaderField:field];
}

+ (void)setupUserAgentOverwrite
{
    [self swizzleMethod:@selector(setValue:forHTTPHeaderField:)
			 withMethod:@selector(newSetValue:forHTTPHeaderField:)];
}

@end


@implementation iPLayer_ipadViewController

@synthesize webView;


/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	Categories *viewController=[[[Categories alloc] initWithNibName:@"Categories" bundle:nil] autorelease];
	viewController.delegate=self;
	UINavigationController *navController=[[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];
	programPopup=[[UIPopoverController alloc] initWithContentViewController:navController];
	[NSMutableURLRequest setupUserAgentOverwrite];
	
	[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.bbc.co.uk/mobile/iplayer"]]];
}



// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return interfaceOrientation==UIDeviceOrientationLandscapeLeft || interfaceOrientation==UIDeviceOrientationLandscapeRight;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	self.webView = nil;

    [super dealloc];
}

-(IBAction) showPrograms:(UIBarButtonItem *) sender {
	[programPopup presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

-(void) showMovie:(NSString *) moviePageUrl {
	NSArray *components=[moviePageUrl componentsSeparatedByString:@"/"];
	// http://www.bbc.co.uk/mobile/iplayer/episode/b00s9kf5
	NSString *mobileURL=[NSString stringWithFormat:@"http://www.bbc.co.uk/mobile/iplayer/episode/%@", [components objectAtIndex:5]];
	[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:mobileURL] 
										  cachePolicy:NSURLRequestReloadRevalidatingCacheData 
									  timeoutInterval:10]];
	[programPopup dismissPopoverAnimated:YES];
}

-  (BOOL) webView:(UIWebView*) webView shouldStartLoadWithRequest:(NSURLRequest*) request navigationType:(UIWebViewNavigationType) navigationType
{
	NSString *str=[request description];
	NSLog(@"%@", str);
	return true;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
	
}
					
-(void) webViewDidFinishLoad:(UIWebView *)theWebView {
//	NSString *pageHtml=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];
//	NSLog(@"%@", pageHtml);
	NSString *js=@"document.getElementsByTagName(\"embed\").length;";
	NSString *res=[webView stringByEvaluatingJavaScriptFromString:js];
	if(res && res.length>0) {
		int embedCount=[res intValue];
		if(embedCount>0) {
			NSString *javascript=
								  @"var embedTag=document.getElementsByTagName('embed')[0];"
								  @"var movieUrl=embedTag.getAttribute('href');"
								  @"var imageTag=embedTag;"
								  @"do { imageTag = imageTag.nextSibling; } "
								  @"while (imageTag && imageTag.nodeType != 1);"
							      @"var previewImage=imageTag.getAttribute('src');"
								  @"var fragment = document.createDocumentFragment(); "
								  @"var videoTag = fragment.appendChild(document.createElement('video'));"
								  @"videoTag.setAttribute('controls', 'yes');"
								  @"videoTag.setAttribute('poster', previewImage);"
								  @"videoTag.setAttribute('width', '800');"
								  @"videoTag.setAttribute('height', '450');"
								  @"var sourceTag = videoTag.appendChild(document.createElement('source'));"
								  @"sourceTag.setAttribute('src', movieUrl);"
								  @"sourceTag.setAttribute('type', 'video/mp4');"
								  @"embedTag.parentNode.removeChild(imageTag);"
								  @"embedTag.parentNode.replaceChild(fragment, embedTag);";
			[webView stringByEvaluatingJavaScriptFromString:javascript];
		}
	}
}

@end
